<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
 * 自定义指令模型类
 */
class msm_weixin_custom_cmd extends ms_model
{
	public $table = 'dbpre_weixin_custom_cmd';
	public $key = 'id';
	public $model_flag = 'weixin';

	public function __construct()
	{
		parent::__construct();
		$this->model_flag = 'weixin';
		$this->modcfg = $this->variable('config');
		$this->init_field();
	}

	/**
	 * 表单提交时需要的字段和过滤
	 */
	public function init_field()
	{
		$this->add_field('mp_id,name,keyword,intro,msgtype,content,is_default,is_subscribe');
		$this->add_field_fun('mp_id,is_default,is_subscribe', MF_INT_KEY);
		$this->add_field_fun('name,keyword,intro,msgtype', MF_TEXT);
		//$this->add_field_fun('content', '_TA');
	}

	public function check_post(&$post, $keyid = FALSE)
	{
		$post['keyword'] = trim($post['keyword']);
		if(!$post['mp_id']) return $this->add_error('对不起，您没有管理绑定的公众平台帐号。');
		if(!$post['name']) return $this->add_error('对不起，您未填写指令名称。');
		if(!$post['intro']) return $this->add_error('对不起，您未填写指令介绍。');
		if(!$post['msgtype']) return $this->add_error('对不起，您未选择回复类型。');
		if(!$post['content']) return $this->add_error('对不起，您未填写回复内容。');

		if($post['msgtype']=='text' && !is_string($post['content'])) return $this->add_error('对不起，您未填写回复内容。');
		if($post['msgtype']=='news' && !is_array($post['content'])) return $this->add_error('对不起，您未填写回复内容。');

		//检测是否和指令类里的冲突
		if($this->exists_keyword_by_cmds($post['keyword'])) {
			return $this->add_error('对不起，您填写的指令关键字与网站内置的指令关键字冲突。');
		}

		//检测是否已经存在关键字
		if($data = $this->exists_keyword($post['mp_id'], $post['keyword'])) {
			if(!$keyid || $keyid != $data['id']) return $this->add_error('对不起，您填写的指令关键字已存在。');
		}

		return $post;
	}

	//检测关键字是否已经存在
	public function exists_keyword($mp_id, $keyword)
	{
		return $this->db->from($this->table)
			->where(array('mp_id'=>$mp_id,'keyword'=>$keyword))
			->get_one();
	}

	public function exists_keyword_by_cmds($keyword)
	{
		return false;
	}

	//更新回复次数
	public function update_replys($num = 1)
	{
		_G('loader')->model('weixin:custom_cmd')->_update_number($this->id, 'replys', $num);
	}

	public function delete_by_mp_id($mp_id)
	{
		return $this->db->from($this->table)
			->where('mp_id', $mp_id)
			->delete();
	}

	//保存更新之前
	protected function _save_befor()
	{
		if($this->_save_data['msgtype']=='news') {
			$array = _T($this->_save_data['content']);
			foreach ($array as $key => $value) {
				if(strposex($value['PicUrl'], '/temp/')) {
					$PicUrl = $this->move_local_picture($value['PicUrl']);
					$array[$key]['PicUrl'] = $PicUrl?$PicUrl:'';
				}
				$array[$key]['Url'] = str_replace(array('&nbsp;','&#38;'), '&', $value['Url']);
			}
			$this->_save_data['content'] = ms_mxml::from_array($array);
		} else {
			$this->_save_data['content'] = _TA($this->_save_data['content']);
		}
		//检测编辑之前旧数据里是否存在冗余的图片
		if($this->_save_on == 'edit') {
			$old_data = $this->current_data;
			if(!$old_data) {
				$old_data = $this->read($this->_save_pkid);
			}
			if($old_data && $old_data['msgtype']=='news') {
				$old_array = ms_mxml::to_array($old_data['content']);
				if($old_array) foreach ($old_array as $key => $value) {
					if($this->_save_data['msgtype'] != 'news') {
						if(strlen($value['PicUrl'])>10) @unlink(MUDDER_ROOT.$value['PicUrl']);
					} else {
						$del = true;
						foreach ($array as $k => $v) {
							if($v['PicUrl']==$value['PicUrl']) $del=false;
						}
						if($del && strlen($value['PicUrl'])>10) @unlink(MUDDER_ROOT.$value['PicUrl']);
					}
				}
			}
		}
	}

	//保存更新之后
	protected function _save_after()
	{
		//is_default,is_subscribe字段具有唯一性，其他自定义指令则重置（同一公众号下）
		if($this->_save_data['is_default']||$this->_save_data['is_subscribe']) {
			
			$set = $where = array();
			$this->_save_data['is_default'] && $set['is_default'] = 0;
			$this->_save_data['is_subscribe'] && $set['is_subscribe'] = 0;
			$where['mp_id'] = $this->_save_data['mp_id'];
			$where['id'] = array('where_not_equal', array($this->_save_pkid));
			
			$this->db->from($this->table)
				->set($set)
				->where($where)
				->update();
		}
	}

	//把上传临时文件夹的图片移动到正式保存文件夹
	protected function move_local_picture($pic)
	{
		$sorcuefile = MUDDER_ROOT . $pic;
		if(!is_file($sorcuefile)) {
			return false;
		}
		if(function_exists('getimagesize') && !@getimagesize($sorcuefile)) {
			@unlink($sorcuefile);
			return false;
		}

		$IMG = new ms_image();
		$IMG->thumb_mod = S('picture_createthumb_mod');

		$path = 'uploads';
		$name = basename($sorcuefile);
		$picture_dir_mod = S('picture_dir_mod');
		if($picture_dir_mod == 'WEEK') {
			$subdir = date('Y', _G('timestamp')) . '-week-' . date('W', _G('timestamp'));
		} elseif($picture_dir_mod == 'DAY') {
			$subdir = date('Y-m-d', _G('timestamp'));
		} else {
			$subdir = date('Y-m', _G('timestamp'));
		}

		$subdir = 'weixin' . DS . $subdir;
		$dirs = explode(DS, $subdir);
		foreach ($dirs as $val) {
			$path .= DS . $val;
			if(!@is_dir(MUDDER_ROOT . $path)) {
				if(!mkdir(MUDDER_ROOT . $path, 0777)) {
					show_error(lang('global_mkdir_no_access',$path));
				}
			}
		}
		$result = array();
		$filename = $path . DS . $name;
		$picture = str_replace(DS, '/', $filename);
		if(!copy($sorcuefile, MUDDER_ROOT . $filename)) {
			return false;
		}

		if(!DEBUG) @unlink($sorcuefile);
		return $picture;
	}

}

/** end **/